package org.crumbleworks.crumbchat.client.console;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.crumbleworks.crumbchat.client.controller.ClientControllerInterface;

public class ConsoleReader implements Runnable {
    private BufferedReader readerFromConsole;
    private ClientControllerInterface controller;

    private boolean isRunning;

    public ConsoleReader(ClientControllerInterface controller) {
        this.controller = controller;
        this.isRunning = true;

        initBufferedReader();
        new Thread(this).start();
    }

    private void initBufferedReader() {
        readerFromConsole = new BufferedReader(new InputStreamReader(System.in));
    }

    private void readInput() {
        String input = null;

        while (isRunning) {
            try {
                input = readerFromConsole.readLine();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }

            controller.parseInput(input);
        }
    }

    public void stop() {
        isRunning = false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void run() {
        readInput();
    }
}
